package com.banzhi.shop.fragment;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.activity.BecomeShoperActivity;
import com.banzhi.shop.activity.ChoiceActivity;
import com.banzhi.shop.activity.CommodityDetailsActivity;
import com.banzhi.shop.activity.CommodityDetails_DZZQActivity;
import com.banzhi.shop.activity.FindAllGoodsActivity;
import com.banzhi.shop.activity.GroupActivity;
import com.banzhi.shop.activity.GroupDayActivity;
import com.banzhi.shop.activity.GroupShopActivity;
import com.banzhi.shop.activity.InviteShopkeeperShareActivity;
import com.banzhi.shop.activity.MainActivity;
import com.banzhi.shop.activity.WebViewActivity;
import com.banzhi.shop.adapter.HomeFrgAda;
import com.banzhi.shop.data.CategoryBean;
import com.banzhi.shop.data.GoodsBean;

import com.banzhi.shop.data.SaleGoodsBean;


import com.banzhi.shop.entity.HomeFrg.HomeFrg_Data;
import com.banzhi.shop.entity.HomeGridView.GridViewAdapter;
import com.banzhi.shop.entity.HomeGridView.IconBean;
import com.banzhi.shop.entity.WXshare;
import com.banzhi.shop.model.CallBack.CommodityDetailsCallBack;
import com.banzhi.shop.model.CallBack.HomeFrgModelCallBack;
import com.banzhi.shop.model.CallBack.ISCanByCallBack;
import com.banzhi.shop.model.CallBack.WXshareCallBack;
import com.banzhi.shop.model.ICommodityDetailsModel;
import com.banzhi.shop.model.IHomeFrgModel;
import com.banzhi.shop.model.IIsCanByModel;
import com.banzhi.shop.model.Impl.CommodityDetailsImpl;
import com.banzhi.shop.model.Impl.HomeFrgModelImpl;
import com.banzhi.shop.model.Impl.IsCanByImpl;
import com.banzhi.shop.model.Impl.WXshareImpl;
import com.banzhi.shop.model.WXshareModel;
import com.banzhi.shop.state.URLString;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.BitmapUtils;
import com.banzhi.shop.utils.CustomToast;
import com.banzhi.shop.utils.EndlessRecyclerOnScrollListener;
import com.banzhi.shop.utils.FastScrollManger;
import com.banzhi.shop.utils.GlideUtils;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.LogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.NumberUtils;
import com.banzhi.shop.utils.ShareUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.view.FlyBanner;
import com.banzhi.shop.view.TitleBar;
import com.banzhi.shop.view.VpSwipeRefreshLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.nostra13.universalimageloader.utils.L;
import com.squareup.picasso.Picasso;
import com.stx.xhb.xbanner.XBanner;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 首页
 */

public class HomeFrg extends Fragment implements HomeFrgModelCallBack, View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, CommodityDetailsCallBack, WXshareCallBack, ISCanByCallBack {
    public static final String TAG = "HomeFrg";
    private View view;
    /**
     * 广告轮播
     */
    private FlyBanner banner;
    /**
     * 分类导航栏
     */
    private TabLayout tabLayout;
    private ViewPager viewPager;
    /**
     * 分类商品选项卡的集合
     */
    private List<String> list = new ArrayList<>();
    /**
     * 轮播图片的集合
     */
    private List<String> imgesUrl = new ArrayList<>();
    /**
     * 页面数据的实体类
     */
    private HomeFrg_Data data;
    private IHomeFrgModel model;

    private VpSwipeRefreshLayout swipeRefreshLayout;
    private AppBarLayout appBarLayout;
    private HomeFrgAda homeFrgAda;
    private ICommodityDetailsModel goodsodel;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bitmap bitmap = (Bitmap) msg.obj;
            showPopupwindow(bitmap);
        }
    };

    private MainActivity activity;
    private ImageView mTemai1;
    private ImageView mPinpaituan1;
    private ImageView mShengxian1;
    private ImageView mQipao1;
    private ImageView mLingyang1;
    private LinearLayout mLlLayoutHomeTop2;
    private RecyclerView mRecyclerView;
    private int page = 1;
    private List<SaleGoodsBean> mSaleGoodsBeans = new ArrayList<>();
    private BaseQuickAdapter<GoodsBean, BaseViewHolder> adapter;
    private int positon;
    /**
     * 时候以添加到店铺的状态值
     */
    private String icon;
    private String wxURL;
    private static final int PENGYOUQUAN = 1;
    private static final int WEIXINHAOYOU = 2;
    private static final int LIANJIE = 3;
    private static final int ERWEIMA = 4;
    private WXshareModel wxmodel;
    private IIsCanByModel canByModel;
    /*新添加GridView部分*/
    private GridView mGridPhoto;
    private List<CategoryBean> mCategoryBeans = new ArrayList<>();
    private ArrayList<IconBean> mData;
    private GridViewAdapter mGridViewAdapter;
    private ImageView mIvTop;

    private XBanner mXBanner;

    private View xbannerView;
    //标识是哪个地方的商品添加到商店   1:标识列表里的商品添加到店铺   2:标识banner轮播里的商品添加到店铺
    private int addShopType = 1;
    //用于标识当前banner的positoon
    private int xbannerPosition;
    private RelativeLayout mXinpintemai;
    //1特卖。2羚羊 3品牌团 4旗袍 5生鲜
    private List<String> ADIUrl = new ArrayList<>();
    private ImageView mIvChoice;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (activity == null) {
            activity = (MainActivity) context;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.frg_home, container, false);
        initView();
        setListeners();
        model = new HomeFrgModelImpl();
        wxmodel = new WXshareImpl();
        canByModel = new IsCanByImpl();
        LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
        model.getData("1", this);
        goodsodel = new CommodityDetailsImpl();
        return view;
    }


    private void initView() {
        mIvChoice = (ImageView) view.findViewById(R.id.iv_choice);
        TitleBar titleBar = (TitleBar) view.findViewById(R.id.tb_home);
        titleBar.setTitle("半职商城");
        titleBar.setRightSkip(R.mipmap.sousuo6, "", this);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.rv);
        mGridPhoto = (GridView) view.findViewById(R.id.grid_photo);
        mIvTop = (ImageView) view.findViewById(R.id.ivtop);
        mLlLayoutHomeTop2 = (LinearLayout) view.findViewById(R.id.ll_layout_home_top2);
        banner = (FlyBanner) view.findViewById(R.id.banner);
        mXBanner = (XBanner) view.findViewById(R.id.xbanner);
        mXinpintemai = (RelativeLayout) view.findViewById(R.id.xinpintemai);
        mTemai1 = (ImageView) view.findViewById(R.id.iv_temai1);
        mPinpaituan1 = (ImageView) view.findViewById(R.id.iv_pinpaituan1);
        mShengxian1 = (ImageView) view.findViewById(R.id.iv_shengxian1);
        mQipao1 = (ImageView) view.findViewById(R.id.iv_qipao1);
        mLingyang1 = (ImageView) view.findViewById(R.id.iv_lingyang1);
        GlideUtils.loadHomeImage(getContext(), mTemai1, URLString.TeMaiURI);
        GlideUtils.loadHomeImage(getContext(), mShengxian1, URLString.ShengXianURI);
        GlideUtils.loadHomeImage(getContext(), mPinpaituan1, URLString.PinPaiTuanURI);
        GlideUtils.loadHomeImage(getContext(), mLingyang1, URLString.LingYangURL);
        GlideUtils.loadHomeImage(getContext(), mQipao1, URLString.QiPaoURI);

        swipeRefreshLayout = (VpSwipeRefreshLayout) view.findViewById(R.id.srl_listview);
        swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.colorWhite);
        swipeRefreshLayout.setColorSchemeResources(R.color.themeColor);
        swipeRefreshLayout.setProgressViewOffset(true, -20, 100);
        swipeRefreshLayout.setOnRefreshListener(this);
        appBarLayout = (AppBarLayout) view.findViewById(R.id.appbar_layout);
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset >= 0) {
                    swipeRefreshLayout.setEnabled(true);
                } else {
                    swipeRefreshLayout.setEnabled(false);
                }
            }
        });

        mIvTop.setVisibility(View.INVISIBLE);

        DisplayMetrics dm = getResources().getDisplayMetrics();
        int width = dm.widthPixels;
        final int height = width * 380 / 800;
        final int height2 = width * 380 / 800 + 450;
        //  int height = width*216/319;

        LinearLayout.LayoutParams params = new AppBarLayout.LayoutParams(width, height);
        LinearLayout.LayoutParams params2 = new AppBarLayout.LayoutParams(width, height2);
        //获取当前控件的布局对象
        //params.height=width;//设置当前控件布局的高度
        banner.setLayoutParams(params);//将设置好的布局参数应用到控件中
        mXBanner.setLayoutParams(params2);


        adapter = new BaseQuickAdapter<GoodsBean, BaseViewHolder>(R.layout.recycleview_items2) {
            @Override
            protected void convert(final BaseViewHolder helper, final GoodsBean item) {
                //标题
                helper.setText(R.id.tv_home_content, item.getTitle());
                //库存
                helper.setText(R.id.tv_kucun, item.getTotal());
                //价格

                if ("0".equals(item.getTotal())) {
                    helper.getView(R.id.img_sold_out).setVisibility(View.VISIBLE);
                }
                if (item.getBegin_price().equals(item.getEnd_price())) {
                    helper.getView(R.id.ll_endprice).setVisibility(View.GONE);
                    if (ASUtils.isCanUse(item.getMarketprice())) {
                        helper.setText(R.id.tv_price, item.getMarketprice());
                    }
                } else {
                    helper.getView(R.id.ll_endprice).setVisibility(View.VISIBLE);
                    if (ASUtils.isCanUse(item.getBegin_price())) {
                        helper.setText(R.id.tv_price, item.getBegin_price());
                    }
                    if (ASUtils.isCanUse(item.getEnd_price())) {
                        helper.setText(R.id.tv_endprice, item.getEnd_price());
                    }
                }
                //图片
                if (ASUtils.isCanUse(item.getThumb())) {
                    Picasso.with(MyApp.context).load(item.getThumb()).placeholder(R.mipmap.zhanweitu).into((ImageView) helper.getView(R.id.img_home));
                }

                if ("1".equals(MyApp.loginMessage.getString("isagent",""))) {                             //店长专区
                    helper.getView(R.id.ll_lirun).setVisibility(View.VISIBLE);
                    helper.getView(R.id.iv_add_dianpu).setVisibility(View.VISIBLE);
                    helper.getView(R.id.iv_fenxiang).setVisibility(View.VISIBLE);
                } else {
                    helper.getView(R.id.ll_lirun).setVisibility(View.INVISIBLE);
                    helper.getView(R.id.iv_add_dianpu).setVisibility(View.INVISIBLE);
                    helper.getView(R.id.iv_fenxiang).setVisibility(View.INVISIBLE);
                    //非店主专区
                }

                    //利润
                    if (ASUtils.isCanUse(item.getProfit())) {
                        helper.setText(R.id.tv_liyun, item.getProfit());
                    }
                    //在售人数
                    helper.setText(R.id.tv_Peoplenum, item.getSharebtn());
                    //是不是加入店铺了
                    if ("0".equals(item.getIcon())) {
                        ((ImageView) helper.getView(R.id.iv_add_dianpu)).setImageResource(R.mipmap.jian1);
                        helper.getView(R.id.iv_add_dianpu).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                addShopType = 1;
                                LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                                model.deleteGoods(item.getId(), null, HomeFrg.this);
                                HomeFrg.this.positon = helper.getLayoutPosition();
                                HomeFrg.this.icon = item.getIcon();
                            }
                        });
                    } else if ("1".equals(item.getIcon())) {
                        ((ImageView) helper.getView(R.id.iv_add_dianpu)).setImageResource(R.mipmap.jia1);
                        helper.getView(R.id.iv_add_dianpu).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                addShopType = 1;
                                LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                                model.AddDianpu(item.getId(), HomeFrg.this);
                                HomeFrg.this.positon = helper.getLayoutPosition();
                                HomeFrg.this.icon = item.getIcon();
                            }
                        });
                    }
                    //保存图片
                    helper.getView(R.id.iv_add_image).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(getActivity(), CommodityDetailsActivity.class);
                            intent.putExtra("id", item.getId());
                            intent.putExtra("type", "1");
                            startActivity(intent);
                        }
                    });
                    //分享
                    helper.getView(R.id.iv_fenxiang).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            wxURL = null;
                            type = 1;
                            showSharePopupwindow(item);
                            HomeFrg.this.positon = helper.getLayoutPosition();
                        }
                    });

            }
        };
        adapter.bindToRecyclerView(mRecyclerView);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapterr, View view, int position) {
                canByModel.getData(adapter.getData().get(position).getId(), HomeFrg.this);
                HomeFrg.this.positon = position;
            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_right:
                Intent intent = new Intent(getActivity(), FindAllGoodsActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_temai1: // 今日特卖
                // ((RadioButton) activity.rgp_main.getChildAt(1)).setChecked(true);
                Intent intent1 = new Intent(getActivity(), GroupActivity.class);
                startActivity(intent1);
/*                Intent intent1 = new Intent(getActivity(), TemaiActivity.class);
                startActivity(intent1);*/
                break;
            case R.id.iv_pinpaituan1: // 品牌团
                startActivity(new Intent(getActivity(), GroupShopActivity.class));
                break;
            case R.id.iv_shengxian1: // （生鲜专区）店长专区(原来的id为-1）
                GroupDayActivity.showDayActivity(getActivity(), "1256", "生鲜专区");
                break;
            case R.id.iv_qipao1: // 旗袍先生馆
                GroupDayActivity.showDayActivity(getActivity(), "1250", "旗袍先生馆");
                break;
            case R.id.iv_lingyang1: // 翎羊早安馆
                GroupDayActivity.showDayActivity(getActivity(), "1233", "羚羊早安馆");
                break;
            case R.id.iv_choice:
                startActivity(new Intent(getContext(), ChoiceActivity.class));
                break;
            default:
                break;
        }
    }

    private void setListeners() {
        mIvChoice.setOnClickListener(this);
        FastScrollManger fastScrollManger = new FastScrollManger(getActivity(), LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(fastScrollManger);
        mRecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(fastScrollManger) {
            @Override
            public void onLoadMore() {
                page++;
                LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                model.getData(page + "", HomeFrg.this);
            }
        });
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
                int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

                // 当不滚动时
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    // 判断是否滚动超过一屏
                    if (firstVisibleItemPosition == 0) {
                        mIvTop.setVisibility(View.INVISIBLE);
                    } else {
                        mIvTop.setVisibility(View.VISIBLE);
                    }

                } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {//拖动中
                    mIvTop.setVisibility(View.INVISIBLE);
                }
            }
        });
        mIvTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRecyclerView.smoothScrollToPosition(0);
            }
        });

        mTemai1.setOnClickListener(this);
        mPinpaituan1.setOnClickListener(this);
        // mShopManagerLayout.setOnClickListener(this);
        mShengxian1.setOnClickListener(this);
        mQipao1.setOnClickListener(this);
        mLingyang1.setOnClickListener(this);
        banner.setOnItemClickListener(new FlyBanner.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (data != null) {
                    if (ASUtils.isCanUse(data.getAdvs().get(position).getLink())) {
                        if (ASUtils.isCanUse(data.getAdvs().get(position).getAction())) {
                            if ("1".equals(data.getAdvs().get(position).getAction())) {
                                goodsodel.getData(data.getAdvs().get(position).getLink(), "0", HomeFrg.this);
                                HomeFrg.this.positon = position;
                            } else if ("2".equals(data.getAdvs().get(position).getAction())) {
                                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                                intent.putExtra("data", data.getAdvs().get(position).getLink());
                                startActivity(intent);
                            }
                        }
                    }
                }
            }
        });

    }

    private Bitmap bitmap;

    @Override
    public void getDataSuccess(Object object) {
        //  mHomeTopLayout.setVisibility(View.VISIBLE);
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
        data = (HomeFrg_Data) object;
        if (page == 1) {
            //展示广告图
            if (data.getBannerInfo() != null) {
                if (!MyApp.loginMessage.getString("bannerid", "").equals(data.getBannerInfo().getId())) {
                    SharedPreferences.Editor editor = MyApp.loginMessage.edit();
                    editor.putString("bannerid", data.getBannerInfo().getId());
                    editor.apply();

                    if (ASUtils.isCanUse(data.getBannerInfo().getThumb())) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Looper.prepare();
                                bitmap = BitmapUtils.returnBitmap(data.getBannerInfo().getThumb());
                                Message message = Message.obtain();
                                message.obj = bitmap;
                                Log.d("bitmap", bitmap + "");
                                handler.handleMessage(message);
                                Looper.loop();
                            }
                        }).start();
                    }
                }
            }
            imgesUrl.clear();
            //获取图片资源并加载图片
            if (data.getAdvs() != null) {
                for (int i = 0; i < data.getAdvs().size(); i++) {
                    imgesUrl.add(data.getAdvs().get(i).getThumb());
                }
            }

            mCategoryBeans.clear();
            if (data.getCategory() != null) {
                for (int i = 0; i < data.getCategory().size(); i++) {
                    mCategoryBeans.add(data.getCategory().get(i));

                }
            }
            adapter.setNewData(data.getGoods()); //这个是第一次添加数据
        } else {
            if (data.getGoods().size() == 0) {
                return;
            }
            adapter.addData(data.getGoods()); //这个是追加新数据
        }

        mSaleGoodsBeans.clear();
        mSaleGoodsBeans.addAll(data.getSaleGoods());
        //  LogUtils.e("jjajjdf",data.getSaleGoods().size()+"");
        setView();


        if (imgesUrl.size() > 0) {
            banner.setImagesUrl(imgesUrl);
        }
        list.clear();
   /*     //获取条目资源
        for (int i = 0; i < data.getCategory().size(); i++) {
            list.add(data.getCategory().get(i).getName());
        }*/
//
        LoadingDialogUtils.dismiss();
    }


    private void setView() {

        //新品特卖
        if (mSaleGoodsBeans.size() != 0) {
            mXBanner.setData(R.layout.recyclerview_items3, mSaleGoodsBeans, null);
        } else {
            mXinpintemai.setVisibility(View.GONE);
            mXBanner.setVisibility(View.GONE);
        }

        mXBanner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(final XBanner xBanner, final Object models, final View view, final int i) {
                ImageView imageView = (ImageView) view.findViewById(R.id.img_home);
                TextView tvHomeContent = (TextView) view.findViewById(R.id.tv_home_content);
                TextView tvKucun = (TextView) view.findViewById(R.id.tv_kucun);
                TextView tvPrice = (TextView) view.findViewById(R.id.tv_price);
                TextView tvLiYun = (TextView) view.findViewById(R.id.tv_liyun);
                TextView tvPeoplenum = (TextView) view.findViewById(R.id.tv_Peoplenum);
                final ImageView mMIvAddDianpu = (ImageView) view.findViewById(R.id.iv_add_dianpu);
                // ImageView iv_jian = (ImageView) view.findViewById(R.id.iv_jian);
                ImageView ivAddImage = (ImageView) view.findViewById(R.id.iv_add_image);
                ImageView ivFenXiang = (ImageView) view.findViewById(R.id.iv_fenxiang);
                if ("1".equals(MyApp.loginMessage.getString("isagent",""))){
                    mMIvAddDianpu.setVisibility(View.VISIBLE);
                    ivFenXiang.setVisibility(View.VISIBLE);
                }else {
                    mMIvAddDianpu.setVisibility(View.INVISIBLE);
                    ivFenXiang.setVisibility(View.INVISIBLE);
                }

                if ("0".equals(mSaleGoodsBeans.get(i).getIcon())) {
                    mMIvAddDianpu.setImageResource(R.mipmap.jian1);
                } else {
                    mMIvAddDianpu.setImageResource(R.mipmap.jia1);
                }
                mMIvAddDianpu.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if ("0".equals(mSaleGoodsBeans.get(i).getIcon())) {
                            addShopType = 2;
                            xbannerView = view;
                            xbannerPosition = i;
                            LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                            model.deleteGoods(mSaleGoodsBeans.get(i).getId() + "", null, HomeFrg.this);
                        } else {
                            addShopType = 2;
                            xbannerView = view;
                            xbannerPosition = i;
                            LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                            model.AddDianpu(mSaleGoodsBeans.get(i).getId() + "", HomeFrg.this);
                        }
                    }
                });

                //跳转到素材
                ivAddImage.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), CommodityDetailsActivity.class);
                        intent.putExtra("id", mSaleGoodsBeans.get(i).getId() + "");
                        intent.putExtra("type", "1");
                        startActivity(intent);
                    }
                });
                //跳转到分享
                ivFenXiang.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        wxURL = null;
                        type = 2;
                        showSharePopupwindow(mSaleGoodsBeans.get(i));
                        HomeFrg.this.positon = i;
                    }

                    private void showSharePopupwindow(final SaleGoodsBean data) {
                        //设置contentView


                        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_share_goods, null);
                        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
                        popWindow.setContentView(contentView);
                        popWindow.setAnimationStyle(R.style.AnimBottom);

                        popWindow.setFocusable(true);
                        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
                        //设置各个控件的点击响应
                        ImageView ivchacha = (ImageView) contentView.findViewById(R.id.iv_chacha);
                        TextView tvprice = (TextView) contentView.findViewById(R.id.tvmoney);
                        TextView tvpricetwo = (TextView) contentView.findViewById(R.id.tv_money_two);
                        LinearLayout llpengyouquan = (LinearLayout) contentView.findViewById(R.id.ll_pengyouquan);
                        LinearLayout llweixin = (LinearLayout) contentView.findViewById(R.id.ll_weixing);
                        LinearLayout lllianjie = (LinearLayout) contentView.findViewById(R.id.ll_lianjie);
                        LinearLayout llerweima = (LinearLayout) contentView.findViewById(R.id.ll_erweima);
                        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
                        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
                        rlbackground.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                popWindow.dismiss();
                            }
                        });
                        ll.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                            }
                        });
                        if (data != null) {
                            tvprice.setText(NumberUtils.DecimalFormat(data.getProfit()));
                            tvpricetwo.setText(NumberUtils.DecimalFormat(data.getProfit()));
                            lllianjie.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (wxURL == null) {
                                        LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                                        wxmodel.getData(data.getId() + "", null, LIANJIE, HomeFrg.this);
                                    } else {
                                        ShareUtils.copyLianjie(getActivity(), wxURL);
                                    }
                                }
                            });
                            llerweima.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (wxURL == null) {
                                        LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                                        wxmodel.getData(data.getId() + "", null, ERWEIMA, HomeFrg.this);
                                    } else {
                                        ShareUtils.ereima3(getActivity(), data.getTitle(), data.getMarketprice(), null, null, null, data.getThumb(), wxURL);
                                    }
                                }
                            });
                            llweixin.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (wxURL == null) {
                                        LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                                        wxmodel.getData(data.getId() + "", null, WEIXINHAOYOU, HomeFrg.this);
                                    } else {
                                        ShareUtils.wxshare(data.getTitle(), data.getThumb(), "全球十佳网商联合出品。匠心工厂，源头供货，正品优品，尽在半职。", wxURL);
                                    }
                                }
                            });
                            llpengyouquan.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (wxURL == null) {
                                        LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                                        wxmodel.getData(data.getId() + "", null, PENGYOUQUAN, HomeFrg.this);
                                    } else {
                                        ShareUtils.wxPengyouquan(data.getTitle(), data.getThumb(), wxURL);
                                    }
                                }
                            });
                        }
                        ivchacha.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                wxURL = null;
                                popWindow.dismiss();
                            }
                        });
                        ColorDrawable dw = new ColorDrawable(0x70000000);
                        popWindow.setBackgroundDrawable(dw);
                        popWindow.showAtLocation(contentView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

                    }

                });
                Glide.with(HomeFrg.this).load(mSaleGoodsBeans.get(i).getThumb()).placeholder(R.mipmap.zhanweitu).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(imageView);
                tvHomeContent.setText(mSaleGoodsBeans.get(i).getTitle());
                tvKucun.setText(mSaleGoodsBeans.get(i).getShowtotal() + "");
                tvLiYun.setText(mSaleGoodsBeans.get(i).getProfit());
                tvPrice.setText(mSaleGoodsBeans.get(i).getMarketprice());
                tvPeoplenum.setText(mSaleGoodsBeans.get(i).getSharebtn() + "");
            }
        });
        mXBanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner xBanner, Object o, View view, int i) {

                Intent intent = new Intent(getActivity(), CommodityDetailsActivity.class);
                intent.putExtra("id", ((SaleGoodsBean) o).getId() + "");
                startActivity(intent);
            }
        });

        mData = new ArrayList<IconBean>();
        for (int i = 0; i < mCategoryBeans.size(); i++) {
            IconBean iconBean = new IconBean();
          //  iconBean.setName(mCategoryBeans.get(i).getName());
            if (!"1".equals(MyApp.loginMessage.getString("isagent",""))&& i== mCategoryBeans.size()-1 ) {
                iconBean.setName("成为店长");
            }else {
                iconBean.setName(mCategoryBeans.get(i).getName());
            }
            iconBean.setAdvimg(mCategoryBeans.get(i).getAdvimg());
            mData.add(iconBean);
        }
        mGridViewAdapter = new GridViewAdapter(getContext(), R.layout.item_grid_icon, mData);
        mGridPhoto.setAdapter(mGridViewAdapter);
        mGridPhoto.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                switch (position) {
                    case 0:
                        GroupDayActivity.showDayActivity(getActivity(), mCategoryBeans.get(0).getId() + "", mCategoryBeans.get(0).getName());
                        break;
                    case 1:
                        GroupDayActivity.showDayActivity(getActivity(), mCategoryBeans.get(1).getId() + "", mCategoryBeans.get(1).getName());
                        break;
                    case 2:
                        GroupDayActivity.showDayActivity(getActivity(), mCategoryBeans.get(2).getId() + "", mCategoryBeans.get(2).getName());
                        break;
                    case 3:
                        GroupDayActivity.showDayActivity(getActivity(), mCategoryBeans.get(3).getId() + "", mCategoryBeans.get(3).getName());
                        break;
                    case 4:
                        GroupDayActivity.showDayActivity(getActivity(), mCategoryBeans.get(4).getId() + "", mCategoryBeans.get(4).getName());
                        break;
                    case 5:
                        GroupDayActivity.showDayActivity(getActivity(), mCategoryBeans.get(5).getId() + "", mCategoryBeans.get(5).getName());
                        break;
                    case 6:
                        GroupDayActivity.showDayActivity(getActivity(), mCategoryBeans.get(6).getId() + "", mCategoryBeans.get(6).getName());
                        break;
                    case 7:
                        GroupDayActivity.showDayActivity(getActivity(), mCategoryBeans.get(7).getId() + "", mCategoryBeans.get(7).getName());
                        break;
                    case 8:
                        //  GroupDayActivity.showDayActivity(getActivity(), mCategoryBeans.get(8).getId() + "", mCategoryBeans.get(8).getName());
                        Intent intent1 = new Intent(getActivity(), GroupActivity.class);
                        startActivity(intent1);

                        break;
                    case 9:
                        if ("1".equals(MyApp.loginMessage.getString("isagent",""))) {
                            startActivity(new Intent(getActivity(), InviteShopkeeperShareActivity.class));
                        }else {
                          //  ToastUtils.makeToastShort("非店长不支持邀请店长");

                  //     startActivity(new Intent(getActivity(), InviteShopkeeperShareActivity.class));
                            if ((MyApp.loginMessage.getString("token","").isEmpty()) ){
                                ToastUtils.makeToastShort("请登录");
                            }else {
                                startActivity(new Intent(getActivity(), BecomeShoperActivity.class));
                            }

                        }

                        break;
                }
            }
        });

    }


    /**
     * 展示分享的popupwindow
     *
     * @param data
     */
    private void showSharePopupwindow(final GoodsBean data) {
        //设置contentView

        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_share_goods, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        //设置各个控件的点击响应
        ImageView ivchacha = (ImageView) contentView.findViewById(R.id.iv_chacha);
        TextView tvprice = (TextView) contentView.findViewById(R.id.tvmoney);
        TextView tvpricetwo = (TextView) contentView.findViewById(R.id.tv_money_two);
        LinearLayout llpengyouquan = (LinearLayout) contentView.findViewById(R.id.ll_pengyouquan);
        LinearLayout llweixin = (LinearLayout) contentView.findViewById(R.id.ll_weixing);
        LinearLayout lllianjie = (LinearLayout) contentView.findViewById(R.id.ll_lianjie);
        LinearLayout llerweima = (LinearLayout) contentView.findViewById(R.id.ll_erweima);
        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        if (data != null) {
            tvprice.setText(NumberUtils.DecimalFormat(data.getProfit()));
            tvpricetwo.setText(NumberUtils.DecimalFormat(data.getProfit()));
            lllianjie.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                        wxmodel.getData(data.getId(), null, LIANJIE, HomeFrg.this);
                    } else {
                        ShareUtils.copyLianjie(getActivity(), wxURL);
                    }
                }
            });
            llerweima.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                        wxmodel.getData(data.getId(), null, ERWEIMA, HomeFrg.this);
                    } else {
                        ShareUtils.ereima3(getActivity(), data.getTitle(), data.getMarketprice(), null, null, null, data.getThumb(), wxURL);
                    }
                }
            });
            llweixin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                        wxmodel.getData(data.getId(), null, WEIXINHAOYOU, HomeFrg.this);
                    } else {
                        ShareUtils.wxshare(data.getTitle(), data.getThumb(), "全球十佳网商联合出品。匠心工厂，源头供货，正品优品，尽在半职。", wxURL);
                    }
                }
            });
            llpengyouquan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                        wxmodel.getData(data.getId(), null, PENGYOUQUAN, HomeFrg.this);
                    } else {
                        ShareUtils.wxPengyouquan(data.getTitle(), data.getThumb(), wxURL);
                    }
                }
            });
        }
        ivchacha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wxURL = null;
                popWindow.dismiss();
            }
        });
        ColorDrawable dw = new ColorDrawable(0x70000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(contentView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }


    @Override
    public void getDataError(Object object) {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
        LoadingDialogUtils.dismiss();
    }


    @Override
    public void AddDianpuSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        //这是提示
        CustomToast.showToast(getActivity(), "上架成功", jsonObject.optString("res"));
        if (addShopType == 1) {   //这里标识是列表商品添加的回调处理
            adapter.getData().get(positon).setIcon("0");
            adapter.notifyItemChanged(positon);
        } else {  //这里是banner轮播商品的处理
            ((ImageView) xbannerView.findViewById(R.id.iv_add_dianpu)).setImageResource(R.mipmap.jian1);
            mSaleGoodsBeans.get(xbannerPosition).setIcon("0");
        }

    }

    @Override
    public void AddDianpuError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void deleteSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        CustomToast.showToast(getActivity(), "下架成功", jsonObject.optString("res"));
        if (addShopType == 1) {   //这里标识是列表商品添加的回调处理
            adapter.getData().get(positon).setIcon("1");
            adapter.notifyItemChanged(positon);
        } else {  //这里是banner轮播商品的处理
            mSaleGoodsBeans.get(xbannerPosition).setIcon("1");
            ((ImageView) xbannerView.findViewById(R.id.iv_add_dianpu)).setImageResource(R.mipmap.jia1);
        }

    }

    /**
     * @param object 删除失败
     */

    @Override
    public void deleteError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));

    }

    @Override
    public void onRefresh() {
        model.getData("1", this);
/*//        显示充值成功的页面和需要的操作
        Intent intent = new Intent();
        intent.setAction("shuaxin");
        getActivity().sendOrderedBroadcast(intent, null);   //有序广播发送*/
//        adapter.notifyDataSetChanged();
        mGridViewAdapter.notifyDataSetChanged();
        swipeRefreshLayout.setRefreshing(false);
    }


    /**
     * 广告弹出图
     *
     * @param bitmap
     */
    private void showPopupwindow(Bitmap bitmap) {
        //设置contentView
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_shouye_guanggao, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);
        popWindow.setAnimationStyle(R.style.AnimBottom);

        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        ImageView ivchacah = (ImageView) contentView.findViewById(R.id.iv_chacha);

        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        ImageView imageView = (ImageView) contentView.findViewById(R.id.iv_image);

        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
        }

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (data != null) {
                    if (ASUtils.isCanUse(data.getBannerInfo().getLink())) {
                        if (ASUtils.isCanUse(data.getBannerInfo().getAction())) {
                            if ("1".equals(data.getBannerInfo().getAction())) {
                                Intent intent = new Intent(getActivity(), CommodityDetailsActivity.class);
                                intent.putExtra("id", data.getBannerInfo().getLink());
                                startActivity(intent);
                            } else if ("2".equals(data.getBannerInfo().getAction())) {
                                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                                intent.putExtra("data", data.getBannerInfo().getLink());
                                startActivity(intent);
                            }
                        }
                    }
                }
                popWindow.dismiss();
            }
        });
        ivchacah.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ColorDrawable dw = new ColorDrawable(0x70000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(contentView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    public void ongetDataSuccess(Object object) {
        Intent intent = new Intent(getActivity(), CommodityDetailsActivity.class);
        intent.putExtra("id", data.getAdvs().get(positon).getLink());
        startActivity(intent);
    }

    @Override
    public void ongetDataError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));

    }

    @Override
    public void getCanBuySuccess(Object object) {
        Intent intent = null;
        if ("1".equals(adapter.getData().get(positon).getIsagentgoods())) {
            intent = new Intent(getActivity(), CommodityDetails_DZZQActivity.class);
        } else {
            intent = new Intent(getActivity(), CommodityDetailsActivity.class);
        }
        intent.putExtra("id", adapter.getData().get(positon).getId());
        startActivity(intent);
    }

    @Override
    public void getCanBuyError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));

    }

    private int type;

    @Override
    public void ongetWXdataSuccess(Object object, int num) {
        LoadingDialogUtils.dismiss();
        WXshare share = (WXshare) object;
        wxURL = share.getRes();
        if (type == 1) {
            if (num == LIANJIE) {
                ShareUtils.copyLianjie(getActivity(), wxURL);
            } else if (num == ERWEIMA) {
                ShareUtils.ereima3(getActivity(), adapter.getData().get(positon).getTitle(), adapter.getData().get(positon).getMarketprice(), null,
                        null, null, adapter.getData().get(positon).getThumb(), wxURL);
            } else if (num == WEIXINHAOYOU) {
                ShareUtils.wxshare(adapter.getData().get(positon).getTitle(), adapter.getData().get(positon).getThumb(), "全球十佳网商联合出品。匠心工厂，源头供货，正品优品，尽在半职。", wxURL);
            } else if (num == PENGYOUQUAN) {
                ShareUtils.wxPengyouquan(adapter.getData().get(positon).getTitle(), adapter.getData().get(positon).getThumb(), wxURL);
            }
        } else if (type == 2) {
            if (num == LIANJIE) {
                ShareUtils.copyLianjie(getActivity(), wxURL);
            } else if (num == ERWEIMA) {
                ShareUtils.ereima3(getActivity(), mSaleGoodsBeans.get(positon).getTitle(), mSaleGoodsBeans.get(positon).getMarketprice(), null,
                        null, null, mSaleGoodsBeans.get(positon).getThumb(), wxURL);
            } else if (num == WEIXINHAOYOU) {
                ShareUtils.wxshare(mSaleGoodsBeans.get(positon).getTitle(), mSaleGoodsBeans.get(positon).getThumb(), "全球十佳网商联合出品。匠心工厂，源头供货，正品优品，尽在半职。", wxURL);
            } else if (num == PENGYOUQUAN) {
                ShareUtils.wxPengyouquan(mSaleGoodsBeans.get(positon).getTitle(), mSaleGoodsBeans.get(positon).getThumb(), wxURL);
            }

        }


    }

    @Override
    public void ongetWXdataError(Object object, int num) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));

    }

    class UpdateTextTask extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask(Context context) {
            this.context = context;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {
            Toast.makeText(context, "开始执行", Toast.LENGTH_SHORT).show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {
            int i = 0;
            while (i < 10) {
                i++;
                publishProgress(i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
            }
            return null;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
            Toast.makeText(context, "执行完毕", Toast.LENGTH_SHORT).show();
        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {
        }
    }

}
